﻿
param
(
    #FQDN to SCCM Server
    [Parameter(Mandatory=$true)][string]$SiteServer,
    [Parameter(Mandatory=$true)][string]$xmlConfigFile
)

$global:userhandle = 0
$global:sid =0
$Global:ws
$Global:ChangeOrderXML

[xml]$xmlConfig = (New-Object System.Net.WebClient).DownloadString("http://$SiteServer/$xmlConfigFile")
[System.Reflection.Assembly]::LoadWithPartialName("System.web")


. "$PSScriptRoot\keepass.ps1"


Function Get-CAServiceDeskLoginCredentials
{
param
(
[Parameter(Mandatory=$true)][xml]$xmlConfiguration
)


$name = $xmlConfiguration.ADRs.Common.ServicedeskUser
#$pass = (FindPasswordInKeePassDBUsingPassword -EntryToFind $name -PasswordToDB (FindPasswordInKeePassDB -EntryToFind "MasterPassword"))
$pass = (FindPasswordInKeePassDB -EntryToFind $name -PathToDB ("$PSScriptRoot\PowerShell$env:USERNAME.kdbx") )

    if($pass -eq $null)
    {
        $pass = FindPasswordInKeePassDB -EntryToFind "myuserforCA"
    }

    if ($global:sid -ne 0) {
        return
    }

        while ($global:userhandle -eq 0)
        {
            $Global:ws = New-WebServiceProxy -Uri $xmlConfiguration.ADRs.Common.ServiceDesk -Class USD_WebServiceSoap -UseDefaultCredential
        
            #////Try to login to ServiceDesk

            #//// Login and get the ID
            $global:sid = $Global:ws.login($name, $pass)

            #//// get the Handle for the userid
            $global:userhandle = $Global:ws.getHandleForUserid($global:sid, $name)

            $counter++
            if($counter -gt 3)
            {
                #Giving up on servicedesk
                break
            }

        }

}

Function Create-CAServiceDeskChangeOrder
{
param
(
    [Parameter(Mandatory=$true)][xml]$xmlConfiguration,
    [Parameter(Mandatory=$true)]$YearMonthToGet,
    [Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation
)

    Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration

    [string]$prop = ""# @()
    $attr = ("persistent_id")
    $requestHandle = @()
    $requestNumber =""

    $CO = $Global:ws.createChangeOrder($global:sid, $global:userhandle, $global:attrVal, $prop, "", $attr, [ref]$requestHandle, [ref]$requestNumber)
    $requestHandle

    if($CO -ne $null)
    {
        Add-CAServiceDeskChangeOrder -MonthToAdd $YearMonthToGet -VisualID $requestNumber -InternalID $requestHandle -XMLChangeFileSaveLocation $XMLChangeFileSaveLocation
    }

              
}

    
Function Create-CAServiceDeskRequest
{
param
(
[Parameter(Mandatory=$true)][xml]$xmlConfiguration
)

    Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration

    [string]$prop = ""# @()
    $attr = ("persistent_id")
    $requestHandle = @()
    $requestNumber =""

    $re = $Global:ws.createRequest($global:sid, $global:userhandle, $global:attrVal, $prop, "", $attr, [ref]$requestHandle, [ref]$requestNumber)
    $requestHandle
    
}


Function Initialize-ChangeOrderXML
{
param
(
[Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation
)

$ChangeOrders ="<ChangeOrders version='1.0'>
    <ChangeOrder>
        <MonthRun>201001</MonthRun>
        <VisualID>00001</VisualID>
        <InternalID>chg:000001</InternalID>
    </ChangeOrder>
</ChangeOrders>
"

    if((Test-Path -Path ($XMLChangeFileSaveLocation)) -eq 0 )
    {
        $ChangeOrders | Out-File $XMLChangeFileSaveLocation
    }
    $Global:ChangeOrderXML = New-Object XML
    $Global:ChangeOrderXML.Load($XMLChangeFileSaveLocation)

}

Function checkIfChangeOrderExistInXML
{
param(

    $MonthToSearch
)
    
    $Found = $false

    foreach($ChangeOrder in $Global:ChangeOrderXML.ChangeOrders.ChangeOrder)
    {

        if($ChangeOrder.MonthRun -eq $MonthToAdd)
        {
            $Found = $true
            break;        
        }

    }
    return $Found

}

Function Get-CAServiceDeskChangeOrder
{
param
(
    [Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation,
    $YearMonthToGet
)

    #always Initialize in case the xml file does not exist
    Initialize-ChangeOrderXML -XMLChangeFileSaveLocation $XMLChangeFileSaveLocation

    $VisualID = $Global:ChangeOrderXML.ChangeOrders.ChangeOrder | where MonthRun -eq $YearMonthToGet | select VisualID
    if($VisualID -eq $null)
    {
        return $null
    }
    else
    {
        return $VisualID.VisualID
    }

}

Function Add-CAServiceDeskChangeOrder
{
param(

    $MonthToAdd,
    $VisualID,
    $InternalID,
    [Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation
)
    
    $Found = $false

    foreach($ChangeOrder in $Global:ChangeOrderXML.ChangeOrders.ChangeOrder)
    {

        if($ChangeOrder.MonthRun -eq $MonthToAdd)
        {
            $Found = $true
            break;        
        }

    }
    if($Found -eq $false )
    {
        $oldChangeOrder = @($Global:ChangeOrderXML.ChangeOrders.ChangeOrder)[0]
        $newChangeOrder = $oldChangeOrder.Clone()
        $newChangeOrder.MonthRun = $MonthToAdd
        $newChangeOrder.VisualID = $VisualID
        $newChangeOrder.InternalID = $InternalID

        $Global:ChangeOrderXML.ChangeOrders.AppendChild($newChangeOrder)

        $Global:ChangeOrderXML.Save($XMLChangeFileSaveLocation)
    }

}


Function Update-CAServiceDeskChangeOrder
{
param(

    $MonthRun,
    $VisualID,
    $InternalID,
    [Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation
)
    
    $Counter = 0

    foreach($ChangeOrder in $Global:ChangeOrderXML.ChangeOrders.ChangeOrder)
    {

        if($ChangeOrder.MonthRun -eq $MonthRun)
        {
            $oldChangeOrder = @($Global:ChangeOrderXML.ChangeOrders.ChangeOrder)[$Counter]
            $newChangeOrder = $oldChangeOrder.Clone()
            $newChangeOrder.MonthRun = $MonthRun
            $newChangeOrder.VisualID = $VisualID
            $newChangeOrder.InternalID = $InternalID
            $Global:ChangeOrderXML.ChangeOrders.ReplaceChild($newChangeOrder,$oldChangeOrder)
            $Global:ChangeOrderXML.Save($XMLChangeFileSaveLocation)
            break;
            
        }
        $Counter +=1

    }

}

Function Test-MainServiceDesk
{
param
(
[Parameter(Mandatory=$true)][xml]$xmlConfiguration
)

    Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration

    $global:attrVal = @("requestor", $global:userhandle, "category", $xmlConfiguration.ADRs.ChangeOrder.ChangeOrderType, "description", "Description", "summary", "Summary","group",$xmlConfiguration.ADRs.ChangeOrder.Group)
    $ChangeID = Create-CAServiceDeskChangeOrder -xmlConfiguration $xmlConfiguration

    $Global:ws.logout($Global:sid)
    $Global:sid = 0

    Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration

    $global:attrVal = @("customer", $global:userhandle, "category", $xmlConfiguration.ADRs.RequestOrder.RequestType, "description", "Description", "summary", "Summary","group",$xmlConfiguration.ADRs.RequestOrder.Group)
    $requestHandle = Create-CAServiceDeskRequest -xmlConfiguration $xmlConfiguration

    $Global:ws.logout($Global:sid)
    $Global:sid = 0

    
}

Function Create-CAServiceDeskRequestForUSBCopyOnDP
{
    PARAM
    (
        [Parameter(Mandatory=$true)][String]$SCCMDP,
        [Parameter(Mandatory=$true)][String]$SCCMDPDescription,
        #Attach to an existing change order
        [Parameter(Mandatory=$true)][String]$ChangeOrder,
        [Parameter(Mandatory=$true)][xml]$xmlConfiguration
    )


#check what DP does not have our package

    Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration

    $Description = $xmlConfiguration.ADRs.RequestOrder.Description -replace "%SCCMDP%", $SCCMDP
    $Description = $Description -replace "%SCCMDPDescription%", $SCCMDPDescription

    $Summary = $xmlConfiguration.ADRs.RequestOrder.Summary -replace "%SCCMDP%", $SCCMDP
    $Summary = $Summary -replace "%SCCMDPDescription%", $SCCMDPDescription

    $global:attrVal = @("customer", $global:userhandle, "category", $xmlConfiguration.ADRs.RequestOrder.RequestType, "description", $Description, "summary", $Summary,"group",$xmlConfiguration.ADRs.RequestOrder.Group)
    #$global:attrVal = @("customer", $global:userhandle, "category", $xmlConfiguration.ADRs.RequestOrder.RequestType, "description", $Description, "summary", $Summary,"group",$xmlConfiguration.ADRs.RequestOrder.Group,"caused_by_chg",$ChangeOrder)
    $requestHandle = Create-CAServiceDeskRequest -xmlConfiguration $xmlConfiguration

    $Global:ws.logout($Global:sid)
    $Global:sid = 0
    $global:userhandle = 0
    
}

Function Create-CAServiceDeskChangeForSecurityPatching
{
param
(
    [Parameter(Mandatory=$true)][xml]$xmlConfiguration,
    [Parameter(Mandatory=$true)][string]$XMLChangeFileSaveLocation,
    $YearMonthToGet
)


    $ChangeOrderID = Get-CAServiceDeskChangeOrder -XMLChangeFileSaveLocation $xmlConfiguration.ADRs.Common.XMLChangeFileSaveLocation -YearMonthToGet $YearMonthToGet
    if($ChangeOrderID -eq $null)
    {

        #Initialize-ChangeOrderXML -XMLChangeFileSaveLocation $XMLChangeFileSaveLocation

        [int]$month = (Get-Date).Month #(Get-Date).Month
        [int]$year = (Get-Date).Year #(Get-Date).Year

        $MonthYearPlus1 = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::FirstMondayOfTheMonth) -Plus1Month ($true)).ToShortDateString().tostring()

        $Summary = $xmlConfiguration.ADRs.ChangeOrder.Summary -replace ($xmlConfiguration.ADRs.ChangeOrder.LookupDates.LookupDate[8]), $MonthYearPlus1
        $Summary

        $Description = $xmlConfiguration.ADRs.ChangeOrder.Description

        $ThirdSundayOfTheMonthPlus1 = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::ThirdSundayOfTheMonth) -Plus1Month ($true)).ToShortDateString().tostring()
        $Description = $Description -replace "%ThirdSundayOfTheMonthPlus1%", $ThirdSundayOfTheMonthPlus1

        $FirstMondayOfTheMonthPlus1 = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::FirstMondayOfTheMonth) -Plus1Month ($true)).ToShortDateString().tostring()
        $Description = $Description -replace "%FirstMondayOfTheMonthPlus1%", $FirstMondayOfTheMonthPlus1

        $ThirdMondayOfTheMonth = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::ThirdMondayOfTheMonth) -Plus1Month ($false)).ToShortDateString().tostring()
        $Description = $Description -replace "%ThirdMondayOfTheMonth%", $ThirdMondayOfTheMonth

        $ForthMondayOfTheMonth = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::ForthMondayOfTheMonth) -Plus1Month ($false)).ToShortDateString().tostring()
        $Description = $Description -replace "%ForthMondayOfTheMonth%", $ForthMondayOfTheMonth

        $ForthSundayOfTheMonth = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::ForthSundayOfTheMonth) -Plus1Month ($false)).ToShortDateString().tostring()
        $Description = $Description -replace "%ForthSundayOfTheMonth%", $ForthSundayOfTheMonth

        $SecondMondayOfTheMonthPlus1 = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::SecondMondayOfTheMonth) -Plus1Month ($true)).ToShortDateString().tostring()
        $Description = $Description -replace "%SecondMondayOfTheMonthPlus1%", $SecondMondayOfTheMonthPlus1

        $FirstDayInThirdWeekOfMonthPlus1 = ([DateTime]($MonthYearPlus1)).AddDays(14).ToShortDateString()
        $Description = $Description -replace "%FirstDayInThirdWeekOfMonthPlus1%", $FirstDayInThirdWeekOfMonthPlus1

        $ForthSundayOfTheMonthPlus1 = (Get-WeekDayInMonth -Month $month -year $year -Day ([DayToReturnInMonth]::ForthSundayOfTheMonth) -Plus1Month ($true)).ToShortDateString().tostring()
        $Description = $Description -replace "%ForthSundayOfTheMonthPlus1%", $ForthSundayOfTheMonthPlus1


                $ReportUrls = $xmlConfiguration.ADRs.ChangeOrder.ReportUrls.ReportUrl
                foreach($ReportUrl in $ReportUrls)
                {
                    $url = [System.Web.HttpUtility]::UrlDecode($ReportUrl.url)
                    $name = $ReportUrl.Name
                    $Description = $Description -replace $name, $url

                }

        #

            Get-CAServiceDeskLoginCredentials -xmlConfiguration $xmlConfiguration
            if($global:userhandle -ne $null)
            {
                $global:attrVal = @("requestor", $global:userhandle, "category", $xmlConfiguration.ADRs.ChangeOrder.ChangeOrderType, "description", $Description, "summary", $Summary,"group",$xmlConfiguration.ADRs.ChangeOrder.Group)
                #$ChangeID = Create-CAServiceDeskChangeOrder
                $counter = 0
                while ($ChangeID -eq $null)
                {
                    $ChangeID = Create-CAServiceDeskChangeOrder -xmlConfiguration $xmlConfiguration -YearMonthToGet $YearMonthToGet -XMLChangeFileSaveLocation $XMLChangeFileSaveLocation
                    $counter++
                    if($counter -gt 3)
                    {
                        #Giving up on servicedesk
                        break
                    }

                }
                $Global:ws.logout($Global:sid)
                $Global:sid = 0
            }
            #todo update CO xml
            $ChangeID
    }

}

Function Create-CAServiceDeskChangeForSecurityPatchingCurrentMonth
{
param
(
    [Parameter(Mandatory=$true)][xml]$xmlConfiguration
)
    #$xmlConfiguration = $xmlConfig
    $YearMonthToGet = ((Get-Date).Year.ToString()) + ((Get-Date).Month.ToString())
    $ChangeOrderID = Get-CAServiceDeskChangeOrder -XMLChangeFileSaveLocation $xmlConfiguration.ADRs.Common.XMLChangeFileSaveLocation -YearMonthToGet $YearMonthToGet
    if($ChangeOrderID -eq $null)
    {
        $ChangeOrderID = Create-CAServiceDeskChangeForSecurityPatching -xmlConfiguration $xmlConfiguration -XMLChangeFileSaveLocation $xmlConfiguration.ADRs.Common.XMLChangeFileSaveLocation -YearMonthToGet $YearMonthToGet
    }



}